/*
 * @Author: EyeSklear 1814580085@qq.com
 * @Date: 2024-01-09 21:35:48
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-03-29 15:08:20
 * @FilePath: \Scene_Back\src\text\text.service.ts
 * @Description:
 *
 * Copyright (c) 2024 by EyeSklear , All Rights Reserved.
 */
import { Injectable, Req } from '@nestjs/common';
import { CreateTextDto } from './dto/create-text.dto';
import { UpdateTextDto } from './dto/update-text.dto';
import { Text } from './entities/text.entity';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class TextService {

  constructor(
    @InjectRepository(Text)
    private readonly textRepository: Repository<Text>,
  ) {}
  async create(createTextDto: CreateTextDto) {
    const text = this.textRepository.create(createTextDto);
    const insertRes = await this.textRepository.insert(text);
    return insertRes.raw;
  }

  async createForScript(createTextDto: CreateTextDto) {
    const insertRes = await this.textRepository.insert(this.textRepository.create(createTextDto));
    return insertRes.raw[0].id;
  }

  async findAll() {
    return this.textRepository.find();
  }
  async findOne(id: string): Promise<Text> {
    return this.textRepository.findOne({ where: { id: id } });
  }

  async findByIds(ids: string[]): Promise<Text[]> {
    return this.textRepository.find({
      where: {
        id: In(ids), // 使用TypeORM的In操作符
      },
    });
  }

  async findUser(creator: string): Promise<Text[]> {
    return this.textRepository.find({ where: { creator: creator } });
  }

  async update(id: string, updateTextDto: UpdateTextDto) {
    const oldText = await this.textRepository.findOne({
      where: { id: id },
    });

    if (!oldText) {
      return '文字条目不存在';
    }
    const updatedText = this.textRepository.merge(oldText, updateTextDto);

    await this.textRepository.save(updatedText);

    // 返回更新后的实体或其他有用的信息
    return updatedText;
  }

  async remove(id: string) {
    try {
      const oldText = await this.textRepository.findOne({
        where: { id: id },
      });
      const result = await this.textRepository.delete({ id: id });
      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
}
